import axios, {AxiosError, AxiosHeaders, HttpStatusCode} from "axios";

axios.defaults.adapter = async (config) => {
  const {
    baseURL, url, method, headers,
    validateStatus, data: requestData, timeout, responseType
  } = config;

  // 设置默认的 Content-Type
  if (!headers['Content-Type']) {
    headers['Content-Type'] = 'application/json'; // 根据需要设置合适的 Content-Type
  }

  let request: UniApp.RequestTask | null = null
  const {statusCode, header, data} = await new Promise<UniApp.RequestSuccessCallbackResult>((resolve, reject) => request = uni.request({
    url: (baseURL || '') + url,
    method: method as UniApp.RequestOptions['method'],
    header: {...headers},
    data: requestData,
    timeout,
    responseType,
    success: resolve,
    fail: reject,
  }))
  const response = {
    data, status: statusCode, headers: AxiosHeaders.from(header), request, statusText: '', config
  }
  if (statusCode === HttpStatusCode.Ok || !validateStatus || validateStatus(statusCode)) return response
  throw new AxiosError(
    'Request failed with status code ' + statusCode,
    [AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(statusCode / 100) - 4],
    config,
    request,
    response
  )
}

export class APIError extends Error {
  name = 'APIError'
}